const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs').promises;
const familyController = require('../controllers/familyController');
const logger = require('../utils/logger');

// 配置头像上传
const avatarStorage = multer.diskStorage({
  destination: async function (req, file, cb) {
    const uploadDir = path.join(__dirname, '../uploads/avatars');
    
    // 确保上传目录存在
    try {
      await fs.mkdir(uploadDir, { recursive: true });
      cb(null, uploadDir);
    } catch (error) {
      logger.error(`创建头像上传目录失败: ${error.message}`);
      cb(error);
    }
  },
  filename: function (req, file, cb) {
    // 生成唯一文件名
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    const ext = path.extname(file.originalname);
    cb(null, 'avatar-' + uniqueSuffix + ext);
  }
});

// 文件过滤器
const imageFilter = (req, file, cb) => {
  // 接受的图片类型
  const allowedMimes = [
    'image/jpeg',
    'image/png',
    'image/gif',
    'image/webp'
  ];
  
  if (allowedMimes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('不支持的文件类型。请上传JPG、PNG、GIF或WEBP格式的图片。'), false);
  }
};

// 配置上传中间件
const upload = multer({
  storage: avatarStorage,
  fileFilter: imageFilter,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB
  }
});

/**
 * @route GET /api/family
 * @desc 获取所有家人信息
 * @access Public
 */
router.get('/', familyController.getAllFamilyMembers);

/**
 * @route GET /api/family/:id
 * @desc 获取单个家人信息
 * @access Public
 */
router.get('/:id', familyController.getFamilyMember);

/**
 * @route POST /api/family
 * @desc 添加家人信息
 * @access Public
 */
router.post('/', familyController.addFamilyMember);

/**
 * @route PUT /api/family/:id
 * @desc 更新家人信息
 * @access Public
 */
router.put('/:id', familyController.updateFamilyMember);

/**
 * @route DELETE /api/family/:id
 * @desc 删除家人信息
 * @access Public
 */
router.delete('/:id', familyController.deleteFamilyMember);

/**
 * @route POST /api/family/:id/avatar
 * @desc 上传家人头像
 * @access Public
 */
router.post('/:id/avatar', upload.single('avatar'), familyController.uploadAvatar);

// 错误处理中间件
router.use((err, req, res, next) => {
  if (err instanceof multer.MulterError) {
    // Multer错误处理
    if (err.code === 'LIMIT_FILE_SIZE') {
      return res.status(400).json({
        success: false,
        message: '文件大小超过限制（最大5MB）'
      });
    }
    
    logger.error(`Multer错误: ${err.message}`);
    return res.status(400).json({
      success: false,
      message: `上传错误: ${err.message}`
    });
  }
  
  // 其他错误
  logger.error(`家人路由错误: ${err.message}`);
  res.status(500).json({
    success: false,
    message: err.message || '服务器内部错误'
  });
});

module.exports = router;